<template>
  <div>
    <el-dialog
      :title="detectorInfo.id ? '编辑探测器' : '新增探测器'"
      :visible.sync="dialogVisible"
      width="860px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="refForm"
        label-width="100px"
        inline
      >
        <!-- <el-form-item size="small" label="所属设备" prop="">
          <div class="value" style="width: 300px">用户传输装置</div>
        </el-form-item>
        <el-form-item size="small" label="设备序列号" prop="">
          <div class="value" style="width: 300px">3532423434</div>
        </el-form-item> -->
        <!-- <span v-if="!detectorInfo.id"> -->
        <el-form-item size="small" label="建筑" prop="buildingId">
          <el-select
            v-model="addForm.buildingId"
            filterable
            placeholder="请选择"
            style="width: 300px"
            @change="changeBuild"
            v-loadMore="loadMore"
          >
            <el-option
              v-for="item in buildList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading"
              :style="loading ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="楼层" prop="floorId">
          <el-select
            v-model="addForm.floorId"
            filterable
            placeholder="请选择"
            style="width: 300px"
            @change="changeFloor"
            v-loadMore="loadMore2"
          >
            <el-option
              v-for="item in floorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading2"
              :style="loading2 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="安装点" prop="spaceId">
          <el-select
            v-model="addForm.spaceId"
            placeholder="请选择"
            style="width: 300px"
            filterable
            v-loadMore="loadMore3"
          >
            <el-option
              v-for="item in spaceList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading3"
              :style="loading3 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="位置标记">
          <div style="display: flex; align-items: center">
            <el-button
              size="small"
              type="primary"
              @click="sign"
              icon="el-icon-location-outline"
              >{{ nameMark }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item size="small" label="探测器型号" prop="detectorType">
          <el-select
            v-model="addForm.detectorType"
            placeholder="请选择"
            style="width: 300px"
            filterable
            @change="detectorTypeChange"
          >
            <el-option
              v-for="item in detectorProductList"
              :key="item.id"
              :label="item.name"
              :value="item.detectorType"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- </span> -->
        <el-form-item size="small" label="探测器名称" prop="detectorName">
          <el-input
            style="width: 300px"
            clearable
            v-model="addForm.detectorName"
            placeholder="请输入"
            maxlength="25"
          ></el-input>
        </el-form-item>
        <el-form-item size="small" label="探测器编码" prop="deviceCode">
          <el-input
            style="width: 300px"
            oninput="value=value.replace(/[\u4e00-\u9fa5]/g,'')"
            @blur="addForm.deviceCode = $event.target.value"
            clearable
            v-model="addForm.deviceCode"
            placeholder="请输入"
            maxlength="25"
          ></el-input>
        </el-form-item>

        <el-form-item size="small" label="主机号" prop="hostNumber">
          <el-input
            style="width: 300px"
            clearable
            v-model="addForm.hostNumber"
            placeholder="请输入"
            maxlength="20"
            @blur="addForm.hostNumber = $event.target.value"
            oninput="value=value.replace(/[^\d]/g,'')"
          ></el-input>
        </el-form-item>

        <el-form-item size="small" label="回路号" prop="circuitNumber">
          <el-input
            style="width: 300px"
            oninput="value=value.replace(/[^\d]/g,'')"
            @blur="addForm.circuitNumber = $event.target.value"
            clearable
            v-model="addForm.circuitNumber"
            placeholder="请输入"
            maxlength="3"
          ></el-input>
        </el-form-item>
        <el-form-item size="small" label="节点号" prop="nodeNumber">
          <el-input
            style="width: 300px"
            oninput="value=value.replace(/[^\d]/g,'')"
            @blur="addForm.nodeNumber = $event.target.value"
            clearable
            v-model="addForm.nodeNumber"
            placeholder="请输入"
            maxlength="3"
          ></el-input>
        </el-form-item>
        <el-form-item size="small" label="备注" prop="remark">
          <el-input
            style="width: 300px"
            clearable
            type="textarea"
            :rows="1"
            autosize
            v-model="addForm.remark"
            placeholder="请输入"
            maxlength="100"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="submit"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <Ichnography ref="refIchnography" @clickMark="clickMark" />
  </div>
</template>

<script>
import {
  reqDetectorAdd,
  reqSpaceManager,
  reqFloorById,
  reqDetectorProductList,
  reqDetectorUpdate,
} from "@api/api.js";
import { validateImei } from "@utils/validate";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import Ichnography from "@/views/deviceList/components/Ichnography.vue";
// import TreeSearchAdd from "@components/TreeSearchAdd.vue";

export default {
  props: ["parentDeviceInfo", "detectorInfo"],
  mixins: [loadMore],
  components: {
    Ichnography,
    // TreeSearchAdd,
  },
  data() {
    return {
      dialogVisible: false,
      buildList: [],
      floorList: [],
      spaceList: [],
      detectorProductList: [],
      addForm: {
        id: "",
        buildingId: "",
        floorId: "",
        spaceId: "",
        targetId: "",
        deviceCode: "",
        hostNumber: "",
        circuitNumber: "",
        nodeNumber: "",
        detectorName: "",
        detectorType: "",
        detectorTypeName: "",
        remark: "",
      },
      rules: {
        buildingId: [
          { required: true, message: "请选择建筑物", trigger: "change" },
        ],
        floorId: [{ required: true, message: "请选择楼层", trigger: "change" }],
        spaceId: [
          { required: true, message: "请选择安装点", trigger: "change" },
        ],
        detectorType: [
          { required: true, message: "请选择探测器型号", trigger: "change" },
        ],
        deviceCode: [
          { required: true, message: "请输入探测器编码", trigger: "blur" },
          // { validator: validateImei },
        ],
        nodeNumber: [
          { required: true, message: "请输入节点号", trigger: "blur" },
        ],
        circuitNumber: [
          { required: true, message: "请输入回路号", trigger: "blur" },
        ],
        hostNumber: [
          { required: true, message: "请输入主机号", trigger: "blur" },
        ],
      },
      loading: false,
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,
      sysInstanceIndex3: 1,
      sysInstanceTotalPages3: 10,
      loading3: false,
      nameMark: "标记",
      mark: "",
      targetId: "",
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    async dialogVisible(e) {
      if (e) {
        this.$nextTick(async () => {
          await this.getBuildList();
          await this.getDetectorProductList();
        });

        if (this.detectorInfo.id) {
          console.log("detectorInfo", this.detectorInfo);
          this.addForm = JSON.parse(JSON.stringify(this.detectorInfo));

          const { mark } = this.detectorInfo;
          this.mark = mark;
          this.nameMark = mark ? "已标记" : "标记";

          await this.getFloorList();
          await this.getSpaceList();
        }
      }
    },
  },
  methods: {
    // 探测器型号列表
    async getDetectorProductList() {
      let res = await reqDetectorProductList({
        parentDeviceType:
          this.parentDeviceInfo.deviceType ||
          this.parentDeviceInfo.parentDeviceType,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.detectorProductList = res.data.list;
    },
    detectorTypeChange(e) {
      this.addForm.detectorTypeName = this.detectorProductList.find(
        (item) => item.detectorType == e
      ).name;
    },
    changeOrgId(instanceId) {
      this.sysInstanceIndex = 1;
      this.addForm.targetId = instanceId.id;
      this.addForm.buildingId = "";
      this.buildList = [];
      this.getBuildList();
    },
    onClear() {
      this.addForm.targetId = this.spacesManage.organizationInfo.orgId;
      this.sysInstanceIndex = 1;
      this.addForm.buildingId = "";
      this.buildList = [];
      this.getBuildList();
    },
    async sign() {
      if (this.addForm.spaceId == "")
        return this.$modal.notifyWarning("请先选择安装点!");
      const res = await reqFloorById(this.addForm.spaceId);
      // console.log(res);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      if (res.data.rows.image == "")
        return this.$modal.notifyWarning("当前楼层暂无平面图,请上传后操作!");
      this.$refs.refIchnography.dialogVisible = true;
      this.$refs.refIchnography.getimage(res.data.rows.image);
      if (this.nameMark == "已标记") {
        this.$refs.refIchnography.getMark(this.mark);
      }
    },
    // 子组件事件
    clickMark(e) {
      // console.log(e);
      this.mark = e;
      this.nameMark = "已标记";
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      await this.getBuildList();
      // 获取列表数据的方法
      this.loading = false;
    },
    // 获取建筑物列表
    async getBuildList() {
      let res = await reqSpaceManager(this.sysInstanceIndex, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.parentDeviceInfo.orgId,
        metaCode: 1,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages = res.data.total;
      this.buildList = [...this.buildList, ...res.data.rows];
      if (this.detectorInfo.id) {
        const { buildingId, spaceName } = this.detectorInfo;
        const index = this.buildList.findIndex(
          (item) => item.id === buildingId
        );
        if (index !== -1) {
          // 如果已存在，检查是否有重复项
          const duplicateIndex = this.buildList.findIndex(
            (item) => item.id === buildingId && !item.orgId
          );
          // 如果找到重复项（没有 orgId 的项），则删除
          if (duplicateIndex !== -1) {
            this.buildList.splice(duplicateIndex, 1);
          }
        } else {
          // 如果不存在，则添加到 buildList 中
          this.buildList = [
            ...this.buildList,
            {
              id: buildingId,
              name: spaceName.split("-")[0], //
            },
          ];
        }
      }
    },
    // 选择建筑物
    changeBuild() {
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.floorList = this.spaceList = [];
      this.addForm.floorId = this.addForm.spaceId = "";
      this.mark = "";
      this.nameMark = "标记";
      this.getFloorList();
    },

    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.getFloorList();
      this.loading2 = false;
    },
    // 获取楼层列表
    async getFloorList() {
      let res = await reqSpaceManager(this.sysInstanceIndex2, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.parentDeviceInfo.orgId,
        parentId: this.addForm.buildingId,
        metaCode: 2,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total;
      this.floorList = [...this.floorList, ...res.data.rows];
      if (
        this.detectorInfo.id &&
        this.addForm.floorId &&
        this.detectorInfo.buildingId === this.addForm.buildingId &&
        this.floorList.length
      ) {
        const { floorId, spaceName } = this.detectorInfo;
        const index = this.floorList.findIndex((item) => item.id === floorId);
        if (index !== -1) {
          // 如果已存在，检查是否有重复项
          const duplicateIndex = this.floorList.findIndex(
            (item) => item.id === floorId && !item.orgId
          );
          // 如果找到重复项（没有 orgId 的项），则删除
          if (duplicateIndex !== -1) {
            this.floorList.splice(duplicateIndex, 1);
          }
        } else {
          // 如果不存在，则添加到 floorList 中
          this.floorList = [
            ...this.floorList,
            {
              id: floorId,
              name: spaceName.split("-")[1], //
            },
          ];
        }
      }
    },
    // 选择楼层
    changeFloor() {
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.spaceList = [];
      this.addForm.spaceId = "";

      this.mark = "";
      this.nameMark = "标记";
      this.getSpaceList();
    },

    async loadMore3() {
      if (this.sysInstanceIndex3 >= Math.ceil(this.sysInstanceTotalPages3 / 10))
        return;
      this.sysInstanceIndex3++;
      this.loading3 = true;
      // 获取列表数据的方法
      await this.getSpaceList();
      this.loading3 = false;
    },
    // 获取安装点列表
    async getSpaceList() {
      let res = await reqSpaceManager(this.sysInstanceIndex3, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.parentDeviceInfo.orgId,
        parentId: this.addForm.floorId,
        metaCode: 3,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages3 = res.data.total;
      this.spaceList = [...this.spaceList, ...res.data.rows];
      console.log(" this.spaceList", this.spaceList);
      if (
        this.detectorInfo.id &&
        this.detectorInfo.buildingId === this.addForm.buildingId &&
        this.addForm.spaceId &&
        this.spaceList.length
      ) {
        console.log(11);
        const { spaceId, spaceName } = this.detectorInfo;
        const index = this.spaceList.findIndex((item) => item.id === spaceId);
        if (index !== -1) {
          // 如果已存在，检查是否有重复项
          const duplicateIndex = this.spaceList.findIndex(
            (item) => item.id === spaceId && !item.orgId
          );
          // 如果找到重复项（没有 orgId 的项），则删除
          if (duplicateIndex !== -1) {
            this.spaceList.splice(duplicateIndex, 1);
          }
        } else {
          console.log({
            id: spaceId,
            name: spaceName.split("-")[2],
          });
          // 如果不存在，则添加到 spaceList 中
          this.spaceList = [
            ...this.spaceList,
            {
              id: spaceId,
              name: spaceName.split("-")[2],
            },
          ];
        }
      }
    },
    // 点击绑定
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        if (!valid) return;
        let {
          id,
          buildingId,
          floorId,
          spaceId,
          deviceCode,
          detectorType,
          detectorTypeName,
          circuitNumber,
          hostNumber,
          nodeNumber,
          detectorName,
          remark,
        } = this.addForm;
        console.log("this.addForm.buildingId", this.addForm.buildingId);
        console.log("this.addForm.floorId", this.addForm.floorId);
        if (this.detectorInfo.id) {
          // 编辑
          const res = await reqDetectorUpdate({
            parentId: this.parentDeviceInfo.id,
            id,

            buildingId,
            floorId,
            spaceId,

            mark: this.mark,
            detectorType,
            detectorTypeName,
            deviceCode,
            circuitNumber,
            hostNumber,
            nodeNumber,
            detectorName,
            remark,
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("编辑成功");
        } else {
          // 新增
          const res = await reqDetectorAdd({
            userId: this.user.userId,
            mark: this.mark,

            buildingId,
            floorId,
            spaceId,

            parentId: this.parentDeviceInfo.id,
            deviceCode,
            detectorType,
            detectorTypeName,
            circuitNumber,
            hostNumber,
            nodeNumber,
            detectorName,
            remark,
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("绑定成功");
        }
        this.closeDialog();
        this.$refs.refIchnography.closeDialog();
        this.$parent.getInit();
      });
    },
    // 点击关闭弹框
    closeDialog() {
      this.$refs.refIchnography.closeDialog();
      //   this.$refs.refTreeSearchAdd.onclose();
      this.$refs.refForm.resetFields();
      this.buildList = [];
      this.floorList = [];
      this.spaceList = [];
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.nameMark = "标记";
      this.mark = "";
      this.addForm = {
        id: "",
        buildingId: "",
        floorId: "",
        spaceId: "",
        targetId: "",
        deviceCode: "",
        circuitNumber: "",
        hostNumber: "",
        nodeNumber: "",
        detectorName: "",
        detectorType: "",
        detectorTypeName: "",
        remark: "",
      };
      this.dialogVisible = false;
    },
  },
  deactivated() {
    if (this.$refs.refIchnography != null || this.$refs.refForm != null) {
      this.closeDialog();
    }
  },
};
</script>

<style lang="less" scoped>
// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 2016;
  // background: red;
  // opacity: 0.5;
}

.value {
  color: @primaryTxtcolor;
}

// 下拉框加载结束

::v-deep .el-loading-mask {
  border-radius: 4px;
}
</style>
